# encodint:utf8

import os
from argparse import ArgumentParser
import sys

from mgamedev.py_lib.luabase import LuabaseTool  # noqa
from mgamedev.py_lib.dhttp import DHttp as DHTTPUtil  # noqa


from ccpm.conffac import PackConf, PluginConf, GConf
from ccpm.net import NetUtil
from ccpm.constants import Constant
from ccpm.conffac import GConf  # noqa
from ccpm.glan import Lan  # noqa
from ccpm import plugins
'''
cod efor execute ccpm plugin
'''

PLUGIN_LIST = [
    "initcfg",
    "upgrade",
    "uploadtool",
    "install",
    "uninstall",
    "publish",
    "unpublish",
    "clean",
    "whoami",
    "adduser",
    "run",
]

__all__ = [
    "Executer"
]


class Executer:

    def __init__(self):
        self.init_conf()
        self.init_util()
        self.init_model()

    def run(self):
        # if (not self.chk_version()):
        #     return
        bin_plugins = dict()
        parser = ArgumentParser(
            prog="ccpm",
            description=Lan.g("CCPM_DESC"),
        )
        parser.add_help = False
        sub_parser = parser.add_subparsers(help="run plugin")
        for plugin in PLUGIN_LIST:
            p = getattr(plugins, plugin)
            bin_plugin = p()
            one_parser = sub_parser.add_parser(bin_plugin.get_info("name"),
                                               help=bin_plugin.get_info("help"))
            bin_plugin.parser_config(one_parser)
            bin_plugins[plugin] = bin_plugin
        ret = parser.parse_args()

        def switch_run(parasnp):
            isplugin = False
            for plgname in PLUGIN_LIST:
                if hasattr(parasnp, plgname):
                    bin_plugins[plgname].try_run(parasnp)
                    isplugin = True
            if (not isplugin):
                print("1111111")
                parser.print_help()
        switch_run(ret)

    def debug_run(self, pluginobj, dicparm):
        pluginobj.run(dicparm)

    def init_conf(self):
        # pass
        pass

    def init_model(self):
        pass

    def init_util(self):
        DHTTPUtil.set_baseurl(GConf().get("host"))

    def chk_version(self):
        ver = GConf().val("__VER__")
        (ok, tip) = NetUtil.bin_chk("123!@#xlmake", ver)
        if not ok:
            print("Chk update raise error!->\n%s", str(tip))
            return False
        else:
            return True
